<template>
    <div>
        <layout-box one="商品管理" two="添加商品">
            <!-- 警告条 -->
            <el-alert center title="添加商品信息" type="info"></el-alert>
            <!-- 步骤条 -->
            <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <!-- tabs区域 -->
            <el-form
                :model="addForm"
                :rules="addFormRules"
                ref="addFormRef"
                label-width="100px"
                label-position="top"
            >
                <!-- tabs上的v-model中的值 对应的就是 被选中的tab-pane中的name的值 -->
                <el-tabs
                    tab-position="left"
                    v-model="activeIndex"
                    :before-leave="beforeTabLeave"
                    @tab-click="tabClicked"
                >
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="addForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="addForm.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="addForm.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类">
                            <!-- 选择商品分类的级联选择框 -->
                            <el-cascader
                                expand-trigger="hover"
                                :options="catelist"
                                :props="cateProps"
                                v-model="addForm.goods_cat"
                                @change="handleChange"
                            ></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <!-- 循环manytabledata -->
                        <!-- 渲染表单的Item项 -->
                        <el-form-item
                            :label="item.attr_name"
                            v-for="item in manyTableData"
                            :key="item.attr_id"
                        >
                            <!-- 复选框组 -->
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox
                                    :label="cb"
                                    v-for="(cb, i) in item.attr_vals"
                                    :key="i"
                                    border=""
                                ></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item
                            :label="item.attr_name"
                            v-for="item in onlyTableData"
                            :key="item.attr_id"
                        >
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload
                            class="upload-demo"
                            action="http://127.0.0.1:8888/api/private/v1/upload"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :headers="headerObj"
                            list-type="picture"
                            :on-success="handleSuccess"
                        >
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor v-model="addForm.goods_introduce"></quill-editor>
                        <br>
                        <el-button type="primary" @click="add">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
            <!-- 预览窗口 -->
            <el-dialog class="imgStyle" title="图片预览" :visible.sync="dialogVisible" width="50%">
                <img :src="previewImg" alt="">
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
                </span>
            </el-dialog>
        </layout-box>
    </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      activeIndex: 0,
      previewImg: "",
      dialogVisible: false,
      catelist: [],
      manyTableData: [],
      onlyTableData: [],
      headerObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      // 这是表单的数据对象
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取所有的商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败！");
      }

      this.catelist = res.data;

      // console.log(this.catelist);
    },
    // 用于限制级联选择器的选择范围
    handleChange() {
      if (this.addForm.goods_cat.length < 3) {
        this.addForm.goods_cat = [];
        return false;
      }
    },
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类！");
        return false;
      }
    },
    async tabClicked() {
      if (this.activeIndex == 1) {
        // 此时说明 处于商品参数tab页 需要获取动态参数列表
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" }
          }
        );

        if (res.meta.status !== 200) {
          return this.$message.error("获取参数列表失败！");
        }
        res.data.forEach(item => {
          // 把动态参数列表中成员内的attr_vals属性由字符串转化为数组
          item.attr_vals = item.attr_vals.split(" ");
        });
        this.manyTableData = res.data;
        console.log(this.manyTableData);
      } else if (this.activeIndex == 2) {
        // 此时说明 处于商品参数tab页 需要获取动态参数列表
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" }
          }
        );

        if (res.meta.status !== 200) {
          return this.$message.error("获取参数列表失败！");
        }
        this.onlyTableData = res.data;
        console.log(this.onlyTableData);
      }
    },
    handleSuccess(res) {
      this.addForm.pics.push({ pic: res.data.tmp_path });
    },
    handlePreview(file) {
      this.previewImg = file.response.data.url;
      this.dialogVisible = true;
    },
    handleRemove(file) {
      // file.response.data.tmp_path
      // 拿上面的值 与 addForm.pics数组中的成员做对比 找到要被删除项的索引
      // findIndex是数组的循环方法
      // findIndex该方法有返回值
      // 把数组中的每一个成员都去跟一个筛选条件做匹配如果匹配了就把第一个匹配到的成员的索引值返回
      // 如果数组所有的成员都没有匹配上 则返回-1
      let i = this.addForm.pics.findIndex(
        item => item.pic == file.response.data.tmp_path
      );
      //   console.log(i);
      this.addForm.pics.splice(i, 1);
      console.log(this.addForm.pics);
    },
    async add() {
      // console.log(this.addForm);
      // 因为添加商品的接口要是addForm中的 goods_cat必须是字符 所以我们要做数组转化为字符串
      // 但是因为级联选择器跟goods_cat做了双向数据绑定 级联选择器组件要求值必须是数组 两个需求冲突了
      // 所以解决办法就是 深拷贝出一个全新的一模一样的对象用于提交表单数据
      const form = _.cloneDeep(this.addForm);
      form.goods_cat = form.goods_cat.join(",");
      // console.log(form);
        this.manyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" ")
          });
        });
        this.onlyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          });
        });
        console.log(form);
        const { data:res } = await this.$http.post('goods',form)
        if(res.meta.status != 201){
            return this.$message.error('添加失败')
        }
        this.$message.success('成功')
        this.$router.push('/goods')
    }
  },
  computed: {
    cateId: function() {
      if (this.addForm.goods_cat.length == 3) {
        return this.addForm.goods_cat[2];
      } else {
        return 0;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.imgStyle {
  text-align: center;
}
</style>